package zx.x.modules.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.kevinsawicki.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import zx.x.modules.app.dao.UserDao;
import zx.x.modules.app.entity.UserEntity;
import zx.x.modules.app.form.LoginForm;
import zx.x.modules.app.service.UserService;
import zx.x.modules.app.utils.JwtUtils;
import zx.x.modules.sys.entity.SysUserTokenEntity;
import zx.x.modules.sys.service.SysUserTokenService;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@Slf4j
@RequestMapping("/app/")
public class WxLogin {
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Value("${renren.jwt.expire}")
    private long expire;

    // 定义字符集（大写字母 + 小写字母 + 数字）
    private static final String CHAR_POOL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    /**
     * 小程序登录
     */
    @PostMapping("/login")
    public Map<String, Object> weixin(UserEntity user){
        Map<String, Object> s = new HashMap<>();
        String openid = "";
        String session_key = "";
        String token = "";

        HttpRequest httpRequest = new HttpRequest("https://api.weixin.qq.com/sns/jscode2session", "GET");
        httpRequest.contentType("application/json", "UTF-8");
        Map<String, Object> data = new HashMap<>();
        data.put("appid", "wx84c015cdc10506cc");
        data.put("secret", "8bada1f2a3ae65cd024993545fc14449");
        data.put("js_code", user.getCode());
        data.put("grant_type", "authorization_code");
        httpRequest.form(data);
        String result = httpRequest.body();
        log.info( "微信小程序返回的result:"+result);
        JSONObject jsonObject = JSON.parseObject(result);
        if (jsonObject.get("openid")==null) {
            s.put("error", jsonObject);
            s.put("code",0);
            return s;
        }
        openid = jsonObject.get("openid").toString();
        session_key = jsonObject.get("session_key").toString();

        // 先查询数据库之前是否登录 如果登录了 就直接把表的给前端 没有就去获取
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<UserEntity>();
        queryWrapper.eq("openid",openid);
        UserEntity userF = userDao.selectOne(queryWrapper);
        // 不存在数据库
        if (userF == null){
            user.setOpenid(openid);
            user.setSessionKey(session_key);
            user.setUsername(user.getName());
            user.setMobile(user.getPhone());
            user.setToken(token);
            user.setPoint(0);
            user.setType(3);
            user.setAuthentication(1);
            userDao.insert(user);

            LoginForm loginForm = new LoginForm();
            loginForm.setOpenid(openid);
            // 用户登录
            long userId = userService.login(loginForm);
            // 生成token
            token = jwtUtils.generateToken(userId);

            // 插入tb_user
            user.setOpenid(openid);
            user.setSessionKey(session_key);
            user.setUsername("微信用户"+(Math.random()*9+1)*100000);
            user.setMobile(user.getPhone());
            user.setToken(token);
            user.setUserId(userId);
            user.setTx("shanghutest/e171cb19d9f28016bec634e42e2e8d71");//头像
            userDao.updateById(user);

            // 插入sys_user_token
            SysUserTokenEntity userTokenObj = new SysUserTokenEntity();
            userTokenObj.setToken(token);
            userTokenObj.setUserId(userId);
            Date nowDate = new Date();
            Date expireDate = new Date(nowDate.getTime() + expire * 99999999);// 过期时间
            userTokenObj.setExpireTime(expireDate);
            userTokenObj.setType(2);
            sysUserTokenService.save(userTokenObj);
        }else {
            // 存在数据库
            openid = userF.getOpenid();
            session_key = userF.getSessionKey();
            token = userF.getToken();
        }
        UserEntity u = userService.queryByOpenId(openid);
        u.setOpenid(null);
        u.setCode(null);
        u.setToken(null);
        u.setSessionKey(null);
        u.setIfJy(null);
        u.setInvitationCode(generateInviteCode(6));//邀请码
        //s.put("openid",openid);
        //s.put("session_key",session_key);
        s.put("token", token);
        s.put("user",u);
        //s.put("expire", jwtUtils.getExpire());
        s.put("code",0);

        return s;
    }



    // 生成指定长度的邀请码
    public String generateInviteCode(int length) {
        Random random = new Random();
        StringBuilder inviteCode = new StringBuilder();
        for (int i = 0; i < length; i++) {
            // 从字符集中随机选择一个字符
            int index = random.nextInt(CHAR_POOL.length());
            inviteCode.append(CHAR_POOL.charAt(index));
        }
        return inviteCode.toString();
    }

}
